package DAO

import (
	"CSMS/database"
	"database/sql"
	"fmt"
	"github.com/gin-gonic/gin"
)

type Indent struct {
	IndentNo         int            `db:"IndentNo"`
	UserNo           int            `db:"UserNo"`
	IndentDate       sql.NullString `db:"IndentDate"`
	IndentTotalPrice int            `db:"IndentTotalPrice"`
	IndentDiscount   float64        `db:"IndentDiscount"`
	IndentRealPrice  float64        `db:"IndentRealPrice"`
}

func (ind *Indent) InsertIndent() int {
	result, err := database.DB.Exec("insert INTO indent(IndentDate,UserNo,IndentTotalPrice,IndentDiscount,IndentRealPrice) values(?,?,?,?,?)", ind.IndentDate, ind.UserNo, ind.IndentTotalPrice, ind.IndentDiscount, ind.IndentRealPrice)
	if err != nil {
		fmt.Printf("Insert failed,err:%v", err)
		return 0
	}
	lastInsertID, err := result.LastInsertId() //插入数据的主键id
	if err != nil {
		fmt.Printf("Get lastInsertID failed,err:%v", err)
		return 0
	}
	fmt.Println("Indent LastInsertID is :", lastInsertID)
	return int(lastInsertID)
}

/*indentList 返回订单对象列表
*用户拥有两个输入，一个是用户号，一个是日期。
*当没有用户号输入时，通过日期来获取
*当有用户号输入时，用户号与日期是与部分
 */
func SLByUserNoORIndentDate(userNo int, indentDate string) []Indent {
	var indentList []Indent
	var rows *sql.Rows
	var err error
	if userNo == 0 || indentDate == "2000-01-01" {
		rows, err = database.DB.Query("SELECT * FROM indent WHERE UserNo=? OR IndentDate=?", userNo, indentDate)
	} else {
		rows, err = database.DB.Query("SELECT * FROM indent WHERE UserNo=? AND IndentDate=?", userNo, indentDate)
	}
	defer func() {
		if rows != nil {
			rows.Close() //可以关闭掉未scan连接一直占用
		}
	}()
	if err != nil {
		fmt.Printf("Query failed,err:%v\n", err)
		return indentList
	}
	var indent Indent
	for rows.Next() {
		err = rows.Scan(&indent.IndentNo, &indent.UserNo, &indent.IndentDate, &indent.IndentTotalPrice, &indent.IndentDiscount, &indent.IndentRealPrice)
		if err != nil {
			fmt.Printf("Scan failed,err:%v\n", err)
		}
		indentList = append(indentList, indent)
	}
	return indentList
}

func SelectFinanceInfo() gin.H {
	var allTotalPrice sql.NullString
	var allTotalPriceReal sql.NullString
	row, err := database.DB.Query("SELECT allIndentTotalPrice,allIndentRealPrice FROM financeinfo")
	if err!=nil {
		fmt.Println("err: ",err)
	}
	row.Next()
	err = row.Scan(&allTotalPrice, &allTotalPriceReal)
	if err!=nil {
		fmt.Println("err: ",err)
	}
	fmt.Println(allTotalPrice,"-",allTotalPriceReal)
	return gin.H{
		"allTotalPrice":     allTotalPrice,
		"allTotalPriceReal": allTotalPriceReal,
	}
}
